package com.falcon.mvc.core;

import com.falcon.mvc.enums.RequestAttrNameEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zongf
 * @date 2024-02-19
 **/
@Slf4j
@Component
public class RequestAttrHolder {

    private Map<RequestAttrNameEnum, ThreadLocal> map = new HashMap<>();

    /** 设置线程变量
     * @param key
     * @param value
     */
    public void set(RequestAttrNameEnum key, Object value) {
        ThreadLocal<Object> local = new ThreadLocal<>();
        local.set(value);
        map.put(key,local);
    }

    /** 获取线程变量
     * @param key key
     * @return 值
     * @param <T>
     */
    public <T> T get(RequestAttrNameEnum key) {
        ThreadLocal threadLocal = map.get(key);
        if (threadLocal == null) {
            return null;
        }
        Object value = threadLocal.get();
        return value == null ? null : (T) value;
    }

    /** 清理变量
     * @param key
     */
    public void clear(RequestAttrNameEnum key) {
        ThreadLocal threadLocal = map.get(key);
        if (threadLocal != null) {
            threadLocal.remove();
            map.remove(key);
        }
    }

    /** 清理所有的 ThreadLocal 变量
     */
    public void clearAll() {
        map.values().forEach(ThreadLocal::remove);
        map.clear();
    }

}
